from configparser import ConfigParser
import os
import sys


# 配置类
class Conf(object):
    def __init__(self):
        self.conf = self.conf_init()
        self.batch_size = int(self.conf['params']['batch_size'])
        self.validation_split = float(self.conf['params']['validation_split'])
        self.img_height = int(self.conf['params']['img_height'])
        self.img_width = int(self.conf['params']['img_width'])
        self.trainable = self.conf['params']['trainable']
        self.class_number = int(self.conf['params']['class_number'])
        self.activation_function = self.conf['params']['activation_function']
        self.model_name = self.conf['model']['model']
        self.monitor = self.conf['early_stopping']['monitor']
        self.patience = self.conf['early_stopping']['patience']
        self.his_dir = self.his_dir_init()
        self.data_dir = self.data_dir_init()

    def conf_init(self):
        conf = ConfigParser()
        conf.read('config.ini')
        print('-------------conf init-------------')
        [[print(k + '=' + conf[s][k]) for k in conf[s]] for s in conf.sections()]
        print('-------------conf end-------------')
        return conf

    def his_dir_init(self):
        his_dir = self.conf['path']['history_dir']
        if os.path.exists(his_dir): return his_dir
        os.mkdir(his_dir)
        return his_dir

    def check_class_number(self, data_dir):
        if len(os.listdir(data_dir)) != self.class_number:
            print('数据集类别数有误，请确认class_number')
            sys.exit(1)

    def data_dir_init(self):
        data_dir = self.conf['path']['data_dir']
        if os.path.exists(data_dir):
            self.check_class_number(data_dir)
            return data_dir
        print('数据集不存在，请确认路径')
        sys.exit(1)
